# -*- coding:utf8 -*-
from django.core.handlers.wsgi import WSGIRequest

__author__ = 'Forcs'

from functools import wraps
from wanbatvpayment.http.whttp import send_error_response_with_message

def require_params(params=None, method="GET"):
    """
    指明请求必要的参数，如果请求中不包涵params中指定的参数名，则直接返回错误结果
    :param params: 必须的参数名
    :param method: 请求方法，默认GET
    :param error_handler: 如果请求中不包涵必要的参数，则用error_handler进行处理
    :return:
    """
    def wrapper(func):
        @wraps(func)
        def wrapped(request, *args, **kwargs):
            req = request
            if not isinstance(req, WSGIRequest):
                for arg in args:
                    if isinstance(arg, WSGIRequest):
                        req = arg
                        break
            if params:
                m = method.upper()
                query = None
                if hasattr(req, m):
                    query = getattr(req, m)

                if params is not None:
                    if query is None:
                        return send_error_response_with_message(
                            message=u'缺少必须参数 %s' % params)

                    for param in params:
                        if param not in query:
                            return send_error_response_with_message(
                                message=u'缺少必须参数 %s' % param)

            return func(request, *args, **kwargs)
        return wrapped
    return wrapper
